package com.zcoj.wx.controller;

import com.zcoj.core.model.ApiResponse;
import com.zcoj.wx.mapper.WxQrCodeMapper;
import com.zcoj.wx.pojo.WxQrCode;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author chenbin
 * @version 1.0
 * @description: TODO
 * @date 2023/8/18 23:49
 */

@RestController
@RequestMapping("/wx/qrCode/{appid}")
public class WxMpQrCodeController {


    @Autowired
    private WxMpQrcodeService wxMpQrcodeService;

    @Autowired
    private WxQrCodeMapper wxQrCodeMapper;

    private final Integer ExpireSecondsHour=3600;//一小时

    private final Integer ExpireSecondsDay=86400;//一天

    /**
     * @method: [qrCodeCreateTmpTicket]
     * @param: [appid]
     * @returns: java.lang.String
     * @description:    获取临时二维码,用户登录 1，或者绑定 2  用户 ||将二维码ticket写入数据库
     * @author: chen.bin
     * @version: 1.0.0
     * @date 2023/8/19 00:29
     **/
    @GetMapping("/getQrCodeCreateTmpTicket/{sceneId}")
    public ApiResponse qrCodeCreateTmpTicket(@PathVariable Integer sceneId) throws WxErrorException{
        WxMpQrCodeTicket wxMpQrCodeTicket = wxMpQrcodeService.qrCodeCreateTmpTicket(sceneId, ExpireSecondsHour);
        WxQrCode wxQrCode = new WxQrCode();
        wxQrCode.setTicket(wxMpQrCodeTicket.getTicket());
        Date date = new Date();
        date.setTime(date.getTime()+wxMpQrCodeTicket.getExpireSeconds()* 1000L);
        wxQrCode.setExpireTime(date);
        //将二维码ticket写入数据库
        wxQrCodeMapper.insert(wxQrCode);
        return ApiResponse.success(wxMpQrCodeTicket);
    }

}
